package service

import (
	"errors"
	"fmt"
	"time"
	"vrcm/src/vrcm/app/admin/models/view"
	"vrcm/src/vrcm/app/admin/service/dto/view_manage"

	"github.com/go-admin-team/go-admin-core/sdk/service"
	cDto "vrcm/src/vrcm/common/dto"
)

type ViewCheck struct {
	service.Service
}

// GetPage 获取ViewCheck列表
func (e *ViewCheck) GetPage(c *view_manage.ViewCheckGetPageReq, list *[]view.ViewCheck, count *int64) error {
	var err error
	var data view.ViewCheck

	err = e.Orm.Model(&data).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
		).
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("ViewCheckService GetPage error:%s \r\n", err)
		return err
	}
	return nil
}

// Get 获取ViewCheck对象
func (e *ViewCheck) Get(d *view_manage.ViewCheckGetReq, models *[]view.ViewCheck) error {

	err := e.Orm.Where(map[string]interface{}{"view_id": d.ViewId, "is_delete": 2}).Find(models).Error
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err
	}
	return nil
}

// Insert 创建ViewCheck对象
func (e *ViewCheck) Insert(c *view_manage.ViewCheckInsertReq) error {
	var err error
	data := make([]view.ViewCheck, 0, 5)
	c.Generate(&data)
	checkInfos := make([]string, 0, 5)
	for _, v := range data {
		checkInfos = append(checkInfos, v.CheckInfo)
	}
	//新增限制信息判断重复
	var model view.ViewCheck
	e.Orm.Where("view_id=? and  check_info in ? and is_delete =2", c.ViewId, checkInfos).First(&model)
	if model.Id > 0 {
		err = errors.New("题目已经存在,请重新创建")
		e.Log.Errorf("SubjectService Insert error:%s \r\n", err)
		return err
	}
	err = e.Orm.Create(&data).Error
	if err != nil {
		e.Log.Errorf("ViewCheckService Insert error:%s \r\n", err)
		return err
	}
	return nil
}

// Update 修改ViewCheck对象
func (e *ViewCheck) Update(c *view_manage.ViewCheckUpdateReq) error {
	var err error
	var data view.ViewCheck
	fmt.Println(c)
	e.Orm.First(&data, c.GetId())
	c.Generate(&data)

	//更新限制信息判断重复
	var model view.ViewCheck
	e.Orm.Where("view_id=? and  check_info in =? and is_delete =2 and id != ?", c.ViewId, c.CheckInfo, c.Id).First(&model)
	if model.Id > 0 {
		err = errors.New("限制信息已经存在,请重新更新")
		e.Log.Errorf("ViewCheckService Insert error:%s \r\n", err)
		return err
	}
	db := e.Orm.Save(&data)
	if err = db.Error; err != nil {
		e.Log.Errorf("ViewCheckService Save error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")
	}
	return nil
}

// Remove 删除ViewCheck
func (e *ViewCheck) Remove(d *view_manage.ViewCheckDeleteReq) error {
	var data view.ViewCheck

	db := e.Orm.Model(&data).Where("id in ?", d.Ids).Update("is_delete", 1)
	if err := db.Error; err != nil {
		e.Log.Errorf("Service RemoveViewCheck error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无该数据")
	}
	return nil
}

// ResetViewCode 重制观看码
func (e *ViewCheck) ResetViewCode(d *view_manage.ResetViewCodeReq) error {
	var data view.ViewCheck

	param := make(map[string]interface{})
	param["is_delete"] = 2
	param["account"] = ""
	param["user_name"] = ""
	param["create_time"] = 0
	db := e.Orm.Model(&data).Where("view_id = ? and check_type = ?", d.ViewId, d.CheckType).Updates(param)
	if err := db.Error; err != nil {
		e.Log.Errorf("Service ResetViewCode error:%s \r\n", err)
		return err
	}
	return nil
}

// UpdateJoinTime 更新加入时间
func (e *ViewCheck) UpdateJoinTime(d *view_manage.UpdateJoinTimeReq) error {
	var data view.ViewCheck

	param := make(map[string]interface{})
	if d.CheckType == 5 {
		param["account"] = d.Account
		param["user_name"] = d.UserName
	}

	param["create_time"] = time.Now().Unix()
	db := e.Orm.Model(&data).Where("view_id = ? and check_type = ? and is_delete = 2 and check_info = ?", d.ViewId, d.CheckType, d.CheckInfo).Updates(param)
	if err := db.Error; err != nil {
		e.Log.Errorf("Service UpdateJoinTime error:%s \r\n", err)
		return err
	}
	return nil
}

// GetViewCodeDetail 获取观看码统计详情
func (e *ViewCheck) GetViewCodeDetail(d *view_manage.GetViewCodeDetailReq) (view_manage.GetViewCodeDetailRes, error) {
	data := make([]view.ViewCheck, 0, 10)
	var res view_manage.GetViewCodeDetailRes

	db := e.Orm.Where("view_id = ? and check_type = ?", d.ViewId, d.CheckType).Find(&data)
	if err := db.Error; err != nil {
		e.Log.Errorf("ViewCheckService GetViewCodeDetail error:%s \r\n", err)
		return res, err
	}
	res.TotalNum = len(data)
	invalidNum := 0
	bindNum := 0
	unUseNum := 0
	for _, v := range data {
		if v.IsDelete == 1 {
			invalidNum++
		}
		if len(v.Account) > 0 && v.IsDelete == 2 {
			bindNum++
		}
		if len(v.Account) <= 0 && v.IsDelete == 2 {
			unUseNum++
		}
	}
	res.CheckType = d.CheckType
	res.ViewId = d.ViewId
	res.BindNum = bindNum
	res.InvalidNum = invalidNum
	res.UnUseNum = unUseNum

	return res, nil
}
